package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
)

type SysExercisesWare struct {
	service.Service
}

func (e SysExercisesWare) Insert(req *dto.SysExercisesWareInsertReq) (int, error) {
	var err error
	var data models.SysExercisesWare

	req.Generate(&data)

	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return 0, err
	}

	return data.Id, nil
}

func (e SysExercisesWare) UpdateQuestionBankWare(req *dto.SysExercisesWareUpdateReq) error {
	var err error
	var model = models.SysExercisesWare{}
	e.Orm.First(&model, req.GetId())
	req.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

func (e SysExercisesWare) Update(req *dto.SysExercisesWareUpdateReq) error {
	var err error
	var model = models.SysExercisesWare{}
	var i int64
	err = e.Orm.Model(&model).Where("name = ?", req.Name).Where("id <> ?", req.Id).Count(&i).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	if i > 0 {
		err = errors.New("子章节已存在！")
		e.Log.Errorf("db error: %s", err)
		return err
	}
	e.Orm.First(&model, req.GetId())
	req.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

func (e SysExercisesWare) DeleteQuestionBankWare(req *dto.SysExercisesWareDeleteByIdReq, p *actions.DataPermission) error {
	var err error
	var data models.ExercisesWareDelete
	var exercisesWareModel models.SysQuestionBankLinkDelete

	return e.Orm.Transaction(func(tx *gorm.DB) error {
		db := tx.Where("id in (?)", req.GetId()).Delete(&data)
		if err = db.Error; err != nil {
			e.Log.Errorf("Error found in  RemoveSysCourseWare : %s", err)
			return err
		}
		if db.RowsAffected == 0 {
			return errors.New("无权删除该数据")
		}

		err = tx.Where("link_id = ?", req.LinkId).
			Where("link_type = ?", 2).
			Where("chapter_id in (?)", req.GetId()).Delete(&exercisesWareModel).Error
		if err != nil {
			return err
		}

		return nil
	})

}

func (e SysExercisesWare) DeleteLargeChapter(req *dto.SysExercisesWareDeleteLargeChapterByIdReq, p *actions.DataPermission) error {
	var err error
	var data models.SysExercisesWare

	return e.Orm.Transaction(func(tx *gorm.DB) error {

		err = tx.Model(&data).
			Scopes(
				actions.Permission(data.TableName(), p),
			).Delete(&data, req.GetId()).Error
		if err != nil {
			return err
		}

		err = tx.Model(&data).
			Scopes(
				actions.Permission(data.TableName(), p),
			).Where("pid = ?", req.GetId()).Delete(&data).Error
		if err != nil {
			return err
		}
		return nil
	})
}
